<?php

/*
CREATE TABLE object (
	id uuid not null,
	relname varchar not null,
	name varchar not null,
	created timestamp not null default now(),
	updated timestamp not null default now(),
	PRIMARY KEY(id)
);
 */

abstract class Agitum_Orm_Object
{
    protected $name;
    protected $title;
    protected $schema = array();
    protected $data = array();
    
    public function __construct()
    {
        $this->init();
        uasort($this->schema, array($this, 'sortByAttr'));
    }
    
    protected function init() 
    {
        $this->name = 'object';
        $this->title = 'Объект';
        
        $this->schema['id'] = Agitum_Orm_Attribute::factory(
            Agitum_Orm_Attirbute_Type::UUID,
            array(
                'name' => 'id',
                'title' => 'Идентификатор',
                'readOnly' => true,
                'sortOrder' => 10,
            )
        );
        
        $this->schema['relname'] = Agitum_Orm_Attribute::factory(
            Agitum_Orm_Attirbute_Type::String,
            array(
                'name' => 'relname',
                'title' => 'Таблица',
                'readOnly' => true,
                'hidden' => true,
                'sortOrder' => 20,
            )
        );
        
        $this->schema['name'] = Agitum_Orm_Attribute::factory(
            Agitum_Orm_Attirbute_Type::String,
            array(
                'name' => 'name',
                'title' => 'Имя',
                'sortOrder' => 30,
            )
        );
        
        $this->schema['created'] = Agitum_Orm_Attribute::factory(
            Agitum_Orm_Attirbute_Type::Timestamp,
            array(
                'name' => 'created',
                'title' => 'дата создания',
                'sortOrder' => 40,
            )
        );
        
         $this->schema['updated'] = Agitum_Orm_Attribute::factory(
             Agitum_Orm_Attirbute_Type::Timestamp,
            array(
                'name' => 'updated',
                'title' => 'дата изменения',
                'sortOrder' => 50,
            )
        );
    }
    
    public function schemaName()
    {
        return array_keys($this->schema);
    }
    
    public function schemaAttr()
    {
        return array_values($this->schema);
    }
    
    public function attr($name)
    {
        if ( isset($this->schema[$name]))
            return $this->schema[$name];
            
        throw new Exception('No attribute '.$name.' in '.__CLASS__.' schema');
    }
    
    private function sortByAttr($a, $b) 
    {
        if ( $a->sortOrder() == $b->sortOrder() ) {
            return 0;
        }
        return $a->sortOrder() > $b->sortOrder() ? +1 : -1;
    }
}